from django import template
import re
from django.core.urlresolvers import reverse
from hakaze.forums.models import Thread
from django.template.defaultfilters import escape,linebreaksbr,urlize,urlencode,linebreaks


register = template.Library()

def genpre(mo):
    match = mo.group(1)
    match = match.replace(u'<br />',u'\n')
    return u'<pre>' + match + u'</pre>'

def encodeurl_1(mo):
    match = mo.group(1)
    return u'<a href="%s">%s</a>' % (match,match)

def encodeurl_2(mo):
    return u'<a href="%s">%s</a>' % (mo.group(1),mo.group(2))

def wikilink(param):
    if param.count(' '):
       firstspace = param.find(' ')
       link = param[:firstspace]
       text = param[firstspace:]
       return  u'<a href="%s">%s</a>' % (reverse('hakaze.wiki.views.wikipage',args=[link]),text)
    return u'<a href="%s">%s</a>' % (reverse('hakaze.wiki.views.wikipage',args=[param]),param)

def macroprocessor(mo):
    commandlist = {
    'hr' : u'<hr/>',
    'img' : u'<img src="%s"/>',
    'wiki' : wikilink,
    }
    word = mo.group(1)
    match = re.match(r'(\w+):(.+)',word)
    if match:
       cmd,param = match.group(1),match.group(2)
       try:
          if callable(commandlist[cmd]):
             return commandlist[cmd](param)
          return commandlist[cmd] % param
       except KeyError:
          pass
    try:
       return commandlist[word]
    except KeyError:
       return word
    return word

def unpack_pre(value):
    pass 

def hakazefy(value,thread):
    if thread:
        channel = thread.channel.codename
    else:
        channel = "#"
    value = value.replace('\r\n','\n')
    value = escape(value)

    # pre tag
    pretagset = (
    u'\&lt\;pre\&gt\;(.+?)\&lt\;\/pre\&gt\;',
    u'\`\`(.+?)\`\`',
    )
    counter = 0
    predata = []
    for tag in pretagset:
        regex = re.compile(tag,re.DOTALL)
        try:
          value = unicode(value,'utf-8')
        except: pass
        value = regex.sub(ur'<pre>\g<1></pre>',value)

    # extract pre tag from text
        regex = re.compile(r'<pre>(.+?)</pre>',re.DOTALL)
        pretag = regex.search(value)
        while pretag:
            predata.append(pretag.group(0))
            value = regex.sub('[{[pre_placeholder_%s]}]' % counter,value, count=1)
            counter += 1
            pretag = regex.match(value)
    if thread: 
        threadurl = reverse('hakaze.forums.views.threadview',args=[channel,thread.get_idinchannel()])
    else:
        threadurl = "#"
    matches = [
    (r'(?m)^==(.+)==',u'<h3>\g<1></h3>'),
    (r'(?m)^=(.+)=',u'<h2>\g<1></h2>'),
    (r'(?m)^ \*\*\* (.+)',u'<span class="listlevel3">\g<1></span>'),
    (r'(?m)^ \*\* (.+)',u'<span class="listlevel2">\g<1></span>'),
    (r'(?m)^ \* (.+)',u'<span class="listlevel1">\g<1></span>'),
    (r'&gt;&gt;(\d+)',u'<a href="%s\g<1>">&gt;&gt;\g<1></a>' % threadurl),
    (r'&#39;&#39;&#39;(.+?)&#39;&#39;&#39;',u'<span style="font-weight:bold">\g<1></span>'),
    (r'&#39;&#39;(.+?)&#39;&#39;',u'<span style="font-style:italic">\g<1></span>'),
    (r'\[\[(.+?) (.+?)\]\]',encodeurl_2),
    (r'\[\[(.+?)\]\]',encodeurl_1),
    (r'{{(.+?)}}',macroprocessor),
    (r'&lt;blockquote&gt;(.+?)&lt;/blockquote&gt;','<blockquote>\g<1></blockquote>'),
    ]
    for match in matches:
        regex = re.compile(match[0])
        value = regex.sub(match[1],value)

    multilinematches = [
    (r'&lt;blockquote&gt;(.+?)&lt;/blockquote&gt;','<blockquote>\g<1></blockquote>'),
    ]
    for match in multilinematches:
        regex = re.compile(match[0],re.DOTALL)
        value = regex.sub(match[1],value)



    value = linebreaks(value)

    # insert back the pre tags
    counter = 0
    for p in predata:
        value = value.replace('[{[pre_placeholder_%s]}]' % counter,p)
        counter += 1
    return value
register.filter(hakazefy)
